# encoding=utf-8
from selenium.webdriver.common.by import By
from LBT.Resource.BaseAtt import BaseAtt


class loginClass(BaseAtt):
    '''
    登录的方法
    '''

    def __init__(self, driver, username="", password="", *otherPar, **otherInfo):
        '''
        构造函数，传递用户名密码，用例id，其他学校等扩展信息。
        :param username: 用户名
        :param password: 密码
        :param otherPar: 封装caseid，来区分用例
        :param otherInfo: 包含学校信息及可能扩展的其他信息
        '''
        self.driver = driver
        self.username = self.lbtUserName
        self.password = self.lbtUserPassword
        self.otherPar = otherPar
        self.otherInfo = otherInfo

    def lbt_open(self, url, *args):
        '''
        通过固定的lbt地址，访问前台
        :param url:
        :return:
        '''
        self.driver.get(url)
        try:
            self.driver.get(url)
        except:
            # 如果网址打不开，尝试三次，如果还不行，就抛出异常。
            i = 0
            if args[0] > 0:
                i = args[0]
            print("尝试打开网址-----" + str(i + 1))
            if i < 3:
                i += 1
                self.driver.close()
                self.lbt_open(i)
            else:
                raise Exception("打开登录地址失败，请重试")
        assert self.on_page(url), '未完成打开乐贝通首页%s' % url

    def on_page(self, url):
        '''验证url是否是当前url'''
        return (self.driver.current_url).__contains__(url)

    def loginClick(self):
        '''
        进行一个普通的登录操作
        :return:
        '''
        self.login_switch_schoolMange()
        self.login_username(self.username)
        self.login_password(self.password)
        self.login_button()

    def loginChoiceSchool(self):
        '''
        进行选择学校的操作
        '''
        btn_role = self.otherInfo.get('btn_rolse')
        schoolname = self.otherInfo.get('schoolname')
        self.choiceSchool(btn_role, schoolname)

    def choiceSchool(self, btn_rolse="", schoolname=""):
        '''封装选择学校操作'''
        allRoles = self.driver.find_elements(By.CLASS_NAME, self.lbt_BtnRole_class)
        for z in allRoles:
            if z.text == self.lbt_schoolname_text:
                z.click()
                break

    def login_username(self, username):
        '''输入用户名'''
        self.driver.find_element(By.ID, 'username').clear()
        self.driver.find_element(By.ID, 'username').send_keys(username)

    def login_password(self, password):
        '''输入密码'''
        self.driver.find_element(By.ID, 'password').clear()
        self.driver.find_element(By.ID, 'password').send_keys(password)

    def login_button(self):
        '''点击登录按钮'''
        self.driver.find_element(By.ID, 'btnLogin').click()

    def login_switch_schoolMange(self):
        '''切换到幼儿园管理页面'''
        self.driver.find_element_by_xpath("//a[contains(@href,'login.jhtml')]").click()

    def assert_login_success(self):
        '''验证是否登录成功'''
        currentName = self.driver.find_element(By.CLASS_NAME, 'name').text
        realName = self.otherInfo.get('realName')
        assert currentName==realName
